﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCS.App.LogManager.Service;

public class JsonDataConvert : IDataConvert
{
    private string NodeName = "";
    private int lastNum = -1;

    public List<PropertyNodeItem> GetTreeModels(string data)
    {
        JObject Jo;
        List<PropertyNodeItem> list = new List<PropertyNodeItem>();
        if (data.Substring(0, 1) == "[" && data.Substring(data.Length - 1, 1) == "]")//判断是否为数组类型
        {
            JArray ja = (JArray)JsonConvert.DeserializeObject(data);
            for (int i = 0; i < ja.Count; i++)
            {
                Jo = (JObject)ja[i];
                foreach (var itemson in Jo)
                {
                    if (lastNum != i)
                    {
                        if (ja[i].Children().Count() > 0)
                        {
                            lastNum = i;
                            list.Add(new PropertyNodeItem() { DisplayName = $"{NodeName}[{i}]", Children = GetTreeModels(ja[i].ToString()) });
                            continue;
                        }
                        else
                            list.Add(new PropertyNodeItem() { DisplayName = itemson.Key, Value = itemson.Value.ToString() });
                    }
                }
            }
        }
        else
        {
            Jo = (JObject)JsonConvert.DeserializeObject(data);
            foreach (var item in Jo)
            {
                if (item.Value.HasValues)
                {
                    NodeName = item.Key;
                    list.Add(new PropertyNodeItem() { DisplayName = item.Key, Children = GetTreeModels(item.Value.ToString()) });
                    continue;
                }
                else
                    list.Add(new PropertyNodeItem() { DisplayName = item.Key, Value = item.Value.ToString() }); ;
            }
        }

        return list;
    }
}